/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.alien.admin.modules.deploy.service.impl;

import com.alien.admin.modules.deploy.domain.DpK8sInstance;
import com.alien.admin.modules.system.domain.User;
import com.alien.admin.modules.system.repository.UserRepository;
import com.alien.admin.utils.*;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.deploy.repository.DpK8sInstanceRepository;
import com.alien.admin.modules.deploy.service.DpK8sInstanceService;
import com.alien.admin.modules.deploy.service.dto.DpK8sInstanceDto;
import com.alien.admin.modules.deploy.service.dto.DpK8sInstanceQueryCriteria;
import com.alien.admin.modules.deploy.service.mapstruct.DpK8sInstanceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zengzhifang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-09-14
 **/
@Service
@RequiredArgsConstructor
public class DpK8sInstanceServiceImpl implements DpK8sInstanceService {

    private final DpK8sInstanceRepository dpK8sInstanceRepository;
    private final DpK8sInstanceMapper dpK8sInstanceMapper;
    private final UserRepository userRepository;

    @Override
    public Map<String, Object> queryAll(DpK8sInstanceQueryCriteria criteria, Pageable pageable) {
        Page<DpK8sInstance> page = dpK8sInstanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(dpK8sInstanceMapper::toDto));
    }

    @Override
    public List<DpK8sInstanceDto> queryAll(DpK8sInstanceQueryCriteria criteria) {
        return dpK8sInstanceMapper.toDto(dpK8sInstanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    /**
     * 根据环境获取命名空间list
     *
     * @param env debug or test or pre or prod
     * @return
     */
    @Override
    public List<String> getNameSpaceListByEnv(String env) {
        DpK8sInstanceQueryCriteria criteria = new DpK8sInstanceQueryCriteria();
        criteria.setEnv(env);
        List<DpK8sInstanceDto> dtoList = dpK8sInstanceMapper.toDto(dpK8sInstanceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        Set<String> result = new HashSet<>();
        for (DpK8sInstanceDto dto : dtoList) {
            String namespaceStr = dto.getNamespaceList();
            if (StringUtils.isBlank(namespaceStr)) {
                return new ArrayList<>();
            }
            String[] arr = namespaceStr.trim().split(",");
            for (String s : arr) {
                result.add(s.trim());
            } // end for arr
        } // end for dtoList

        return Lists.newArrayList(result);
    }

    @Override
    @Transactional
    public DpK8sInstanceDto findById(Integer id) {
        DpK8sInstance dpK8sInstance = dpK8sInstanceRepository.findById(id).orElseGet(DpK8sInstance::new);
        ValidationUtil.isNull(dpK8sInstance.getId(), "DpK8sInstance", "id", id);
        return dpK8sInstanceMapper.toDto(dpK8sInstance);
    }

    @Override
    @Transactional
    public DpK8sInstanceDto findFirstByEnv(String env) {
        DpK8sInstance dpK8sInstance = dpK8sInstanceRepository.findFirstByEnv(env);
        if (dpK8sInstance == null) {
            dpK8sInstance = new DpK8sInstance();
        }
        ValidationUtil.isNull(dpK8sInstance.getId(), "DpK8sInstance", "env", env);
        return dpK8sInstanceMapper.toDto(dpK8sInstance);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DpK8sInstanceDto create(DpK8sInstance resources) {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        resources.setCreateBy(user.getUsername());
        resources.setUpdateBy(user.getUsername());
        resources.setCreateTime(timestamp);
        resources.setUpdateTime(timestamp);

        return dpK8sInstanceMapper.toDto(dpK8sInstanceRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DpK8sInstance resources) {
        DpK8sInstance dpK8sInstance = dpK8sInstanceRepository.findById(resources.getId()).orElseGet(DpK8sInstance::new);
        ValidationUtil.isNull(dpK8sInstance.getId(), "DpK8sInstance", "id", resources.getId());

        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        resources.setUpdateBy(user.getUsername());
        dpK8sInstance.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        dpK8sInstance.copy(resources);
        dpK8sInstanceRepository.save(dpK8sInstance);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            dpK8sInstanceRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DpK8sInstanceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DpK8sInstanceDto dpK8sInstance : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("k8s实例的名称", dpK8sInstance.getName());
            map.put("环境", dpK8sInstance.getEnv());
            map.put("k8s的配置内容", dpK8sInstance.getContent());
            map.put("创建人", dpK8sInstance.getCreateBy());
            map.put("修改人", dpK8sInstance.getUpdateBy());
            map.put("创建日期", dpK8sInstance.getCreateTime());
            map.put("更新时间", dpK8sInstance.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}